/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.dataie.rest;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ibm.iisp.common.exception.I18nAppException;
import com.ibm.iisp.common.vo.PagedQueryResult;
import com.ibm.iisp.common.vo.RefBean;
import com.ibm.iisp.common.vo.RestResult;
import com.ibm.iisp.dataie.model.DataIETable;
import com.ibm.iisp.dataie.model.DataIETemplate;
import com.ibm.iisp.dataie.model.DataImport;
import com.ibm.iisp.dataie.model.DataImportAction;
import com.ibm.iisp.dataie.model.DataImportAction.Action;
import com.ibm.iisp.dataie.service.DataIEService;
import com.ibm.iisp.dataie.vo.DataExportRequest;
import com.ibm.iisp.dataie.vo.DataImportQueryParam;
import com.ibm.iisp.dataie.vo.NodeImportState;

/**
 * 类作用：
 * 
 * @author Johnny@cn.ibm.com 使用说明：
 */
@RestController
@RequestMapping("/iisp-data-ie")
public class DataIEResource {
	@Inject
	DataIEService service;

	@GetMapping("/templates")
	public List<DataIETemplate> getImportTemplatesByTable(@RequestParam("tableName") String tableName) {
		List<DataIETemplate> temps = service.getDataIETemplatesByTable(tableName);
		return temps;
	}
	
	

	@GetMapping("/exportRequests/tables/{table}")
	public DataExportRequest getDataExportReqByName(@PathVariable("table") String tableName,
			@RequestParam(name = "useTemplate", required = false) String useTemplate) {
		return service.getDataExportRequestByName(tableName, "Y".equalsIgnoreCase(useTemplate));
	}

	@GetMapping("/exportRequests/templates/{id}")
	public DataExportRequest getDataExportReqByTemplate(@PathVariable("id") Long templateId) {
		return service.getDataExportRequestByTemplate(templateId);
	}

	// @Path("/exports")
	// @GET
	// public List<DataExport> getDataExportsByTable(@RequestParam("tableName") String tableName) {
	// return service.getDataExportsByTable(tableName);
	// }

	@DeleteMapping("/templates/{id}")
	public void delTemplate(@PathVariable("id") Long id) {
		service.delDataIETemplate(id);
	}

	@PostMapping("/imports")
	public DataImport dataImportRequest(@RequestParam(name = "approved", required = false) Boolean approved, DataImport dataImport) {
		dataImport.setImportMessage("Upload datafile for review.");
		try {
			dataImport = service.dataImportRequest(dataImport, Boolean.TRUE.equals(approved));
		} catch (I18nAppException e) {
			if (dataImport.getId() != null) {
				DataImport oDi = service.getDataImport(dataImport.getId());
				if (oDi != null) {
					dataImport.setLastUpdateTime(oDi.getLastUpdateTime());
				}
				dataImport.setImportState(DataImport.State.ERROR);
				dataImport.setImportMessage(e.getMessage());
				service.updateDataImport(dataImport);
			}
		}
		return dataImport;
	}

	@PostMapping("/imports/{id}")
	public DataImport dataImportExecute(@PathVariable("id") Long id, DataImportAction action) throws I18nAppException {
		try {
			return service.dataImportExecute(id, action);
		} catch (I18nAppException e) {
			if (action.getAction() == Action.APPROVE) {
				action.setAction(Action.ERROR);
				String message = e.getMessage();
				if (message == null) {
					message = e.getErrorCode();
				}
				action.setMessage(message);
				service.dataImportExecute(id, action);
			}
			throw e;
		}
	}

	@PostMapping("/exports")
	public RestResult exportData(DataExportRequest dataExportDef) throws I18nAppException {
		String filepath = service.exportData(dataExportDef);
		return new RestResult(filepath);
	}

	@GetMapping("/imports")
	public PagedQueryResult<DataImport> searchImportData(DataImportQueryParam param) {
		PagedQueryResult<DataImport> dataImports = service.searchDataImports(param);
		return dataImports;
	}

	@PutMapping("/templates/{id}")
	public void newTemplate(@PathVariable("id") Long id, DataIETemplate template) throws I18nAppException {
		service.saveTemplate(template);
	}

	@PostMapping("/templates")
	public DataIETemplate newTemplate(@RequestParam(name = "genDefault", required = false) String genDefault, DataIETemplate template)
			throws I18nAppException {
		if ("Y".equalsIgnoreCase(genDefault)) {
			return service.genDefaultTemplate(template.getTabName());
		}
		return service.saveTemplate(template);
	}

	@PutMapping("/templates")
	public void updateTemplate(DataIETemplate template) throws I18nAppException {
		service.saveTemplate(template);
	}

	@GetMapping("/tables")
	public List<DataIETable> getDataIETables() {
		List<DataIETable> tables = service.getDataIETables();
		// 清除不必要输出的字段
		for (DataIETable tb : tables) {
			tb.setDefaultFilter(null);
			tb.setKeyColumns(null);
			tb.setRequiredCoumns(null);
			tb.setNodeDataFilter(null);
		}
		return tables;
	}

	@GetMapping("/node-import-tables")
	public List<RefBean> getNodeImportTables() {
		List<DataIETable> tables = service.getNodeImportTables();
		List<RefBean> tbs = new ArrayList<>(tables.size());
		for (DataIETable tb : tables) {
			tbs.add(new RefBean(tb.getCode(), tb.getName()));
		}
		return tbs;
	}

	@GetMapping("/node-import-states/tables/{tableCode}")
	public List<NodeImportState> getNodeImportStates(@PathVariable("tableCode") String tableCode, @RequestParam("dataDate") String dataDate) {
		return service.getDataImportStateByTableAndDate(tableCode, dataDate);
	}
}
